package com.wframe.project.jnd.util;

import com.wframe.project.jnd.entity.PurchaseGiftItem;
import com.wframe.project.jnd.entity.PurchaseGiftProduct;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by lwb on 2017/6/7.
 */
public class PurchaseGiftPromotionHandlerChain {
    private List<PurchaseGiftItem> items;

    private PurchaseGiftPromotionHandler handler;

    public PurchaseGiftPromotionHandlerChain(List<PurchaseGiftItem> items) {
        Assert.notEmpty(items, "满赠促销必须有赠品");
        this.items = items;
        setHandler();
    }

    private void setHandler() {
        int size = this.items.size();
        int i = 0;
        this.handler = new PurchaseGiftPromotionHandler(this.items.get(0));
        if (size > 1) {
            addHandler(this.handler, this.items.get(++i), i);
        }
    }

    private void addHandler(PurchaseGiftPromotionHandler handler, PurchaseGiftItem item, int i) {
        PurchaseGiftPromotionHandler next = new PurchaseGiftPromotionHandler(item);
        handler.setSuccessor(next);
        if (i == this.items.size() - 1) {
            return;
        }
        addHandler(next, this.items.get(++i), i);
    }

    public PurchaseGiftItem handlePrice(BigDecimal totalPrice) {
        return this.handler.handleRequest(totalPrice);
    }

    public PurchaseGiftItem handleAmount(int totalAmount) {
        return this.handler.handleRequest(totalAmount);
    }
}
